package v1

import (
    "ginBlog/service"
    "ginBlog/utils"
    "github.com/gin-gonic/gin"
    "net/http"
    "strconv"
)

func GetAllCategory(c *gin.Context)  {
    cates, e := service.Category{}.GetAll()
    if e != nil {
        c.JSON(http.StatusInternalServerError, utils.GenResponse(40008, nil, e))
        return
    }
    c.JSON(http.StatusOK, utils.GenResponse(20000, cates, nil))
}

func CreateCategory(c *gin.Context)  {
    category := &service.Category{}
    if e := c.ShouldBindJSON(category); e != nil {
       c.JSON(http.StatusBadRequest, utils.GenResponse(40000, nil, e))
        return
    }
    cate, e := category.Create()
    if e != nil {
        c.JSON(http.StatusInternalServerError, utils.GenResponse(40009, nil, e))
        return
    }
    c.JSON(http.StatusOK, utils.GenResponse(20000, cate, e))
}

func DeleteCategory(c *gin.Context)  {
    id, _ := strconv.Atoi(c.Param("id"))
    r := service.Category{ID: id}
    category, i := r.GetOne()
    if i != nil {
        c.JSON(http.StatusNotFound, utils.GenResponse(40006, nil, i))
        return
    }

    if e := category.Delete(); e !=nil{
        c.JSON(http.StatusInternalServerError, utils.GenResponse(40001, nil, e))
        return
    }
    c.JSON(http.StatusOK, utils.GenResponse(20000, category, nil))

}

func EditCategory(c *gin.Context)  {
    id, _ := strconv.Atoi(c.Param("id"))
    cate := service.Category{ID: id}
    if e := c.ShouldBindJSON(&cate); e != nil {
        c.JSON(http.StatusBadRequest, utils.GenResponse(40000, nil, e))
        return
    }
    if e := cate.Edit(); e != nil {
        c.JSON(http.StatusInternalServerError, utils.GenResponse(40010, nil, e))
        return
    }
    c.JSON(http.StatusOK, utils.GenResponse(20000, cate, nil))
}











